<template>
  <div id="app">
    <div class="search">
     <span>
       时间：<el-date-picker
         v-model="sateValue"
         type="daterange"
         range-separator="至"
         clearable
         size="small"
         @change="selectTime"
         style="width: 300px"
         start-placeholder="开始日期"
         end-placeholder="结束日期"
     >
      </el-date-picker>
     </span>
      <span style="margin-left: 10px">
        姓名：<el-input size="small" style="width: 200px" v-model="installers" placeholder="请输入姓名" clearable></el-input>
      </span>
      <span style="margin-left: 10px">
        店铺名称：<el-input size="small" style="width: 200px" v-model="storeName" placeholder="请输入店铺名称" clearable></el-input>
      </span>
      <span style="text-align: center;margin-left: 20px">所属仓库：
        <el-select v-model="areaId" clearable placeholder="请按区域搜索" size="small" style="width: 180px">
          <el-option v-for="item in areaData" :key="item.area" :label="item.areaName" :value="item.area">
          </el-option>
        </el-select>
      </span>
      <span style="text-align: center;margin-left: 20px">所属品牌： <el-select clearable v-model="systemType"
                                                                          placeholder="请按品牌方搜索"
                                                                          size="small" style="width: 200px">
           <el-option
               v-for="item in systemTypeData"
               :key="item.id"
               :label="item.systemName"
               :value="item.id"
           >
          </el-option>
        </el-select></span>
      <!--      <span style="margin-left: 10px">-->
      <!--        状态：<el-select v-model="isCancelCommission">-->
      <!--        <el-option label="正常" value="0"></el-option>-->
      <!--        <el-option label="已取消" value="1"></el-option>-->
      <!--      </el-select>-->
      <!--      </span>-->
      <el-button size="small" type="primary" style="margin-left: 10px" @click="search">搜索</el-button>
      <div class="download" style="float: right">
        <!--        <el-button type="primary" size="small" @click="downloadTotal">-->
        <!--          <i class="el-icon-download"></i>-->
        <!--          提成汇总下载-->
        <!--        </el-button>-->
        <el-dropdown @command="downloadTotal">
          <el-button type="primary" v-if="authority.includes(1102)" size="small">
            <i class="el-icon-download"></i>
            提成汇总下载
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item :command="''">全部</el-dropdown-item>
            <el-dropdown-item :command="item.id" v-for="item in systemTypeData">{{ item.systemName }}</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </div>
    <div class="table" style="margin-top: 20px">
      <el-tabs v-model="activeName" @tab-click="getReportList" type="border-card">
        <el-tab-pane label="安装列表" name="1">
          <el-button type="primary" v-if="authority.includes(1104)" size="small" style="float: right;margin-bottom: 10px" @click="load_az('安装')"><i
              class="el-icon-download"></i>安装提成下载
          </el-button>
          <el-button v-if="authority.includes(1103)" type="primary" size="small" style="float: right;margin-bottom: 10px;margin-right: 10px"
                     @click="load_azer('安装')"><i
              class="el-icon-download"></i>按安装人员下载
          </el-button>
          <el-table :data="reportData" border height="calc(100vh - 350px)"
                    :headerCellStyle="{
              textAlign: 'center',
              'background': '#66b1ff',
              'color': 'white',
            }" :cellStyle="{ textAlign: 'center', 'font-size': '12px' }">
            <el-table-column prop="installers" label="安装人员"></el-table-column>
            <el-table-column prop="areaName" label="所属仓库"></el-table-column>
            <el-table-column label="类型">
              <template slot-scope="scope">
                <span v-if="scope.row.orderType==1">新店</span>
                <span v-if="scope.row.orderType==2">老店</span>
              </template>
            </el-table-column>
            <el-table-column prop="storeName" label="店铺名称"></el-table-column>
            <el-table-column label="营业区转化图">
              <template v-slot:default="scope">
                <el-image
                    v-if="scope.row.cadImg"
                    style="width: 50px"
                    src="https://qiniushelves.jiachuangnet.com/shelf/img/%E6%9F%A5%E7%9C%8B%E8%AF%A6%E6%83%85.png"
                    :preview-src-list="Array('https://'+scope.row.cadImg)"
                ></el-image>
              </template>
            </el-table-column>
            <el-table-column label="仓库转化图">
              <template v-slot:default="scope">
                <el-image
                    v-if="scope.row.storageImg"
                    style="width: 50px"
                    src="https://qiniushelves.jiachuangnet.com/shelf/img/%E6%9F%A5%E7%9C%8B%E8%AF%A6%E6%83%85.png"
                    :preview-src-list="Array('https://'+scope.row.storageImg)"
                ></el-image>
              </template>
            </el-table-column>
            <el-table-column prop="commissionFee" label="单次提成"></el-table-column>
            <el-table-column prop="deliveryDate" label="安装日期"></el-table-column>
            <!--            <el-table-column label="总提成">-->
            <!--              <template slot-scope="scope">-->
            <!--                <span style="color: orangered">{{ (scope.row.totalCommissionFee).toFixed(2) }}</span>-->
            <!--              </template>-->
            <!--            </el-table-column>-->
            <el-table-column label="状态">
              <template slot-scope="scope">
                <span v-if="scope.row.isCancelCommission==0">正常</span>
                <span style="color: orangered" v-if="scope.row.isCancelCommission==1">已取消提成</span>
              </template>
            </el-table-column>

          </el-table>
          <el-pagination style="padding: 20px 0;" align="right" @size-change="handleSizeChange"
                         @current-change="handleCurrentChange" :current-page="currentPage"
                         :page-sizes="[20, 30, 40, 50]"
                         layout="total, sizes, prev, pager, next, jumper" :total="totalCount">
          </el-pagination>

        </el-tab-pane>
        <el-tab-pane label="拣货列表" name="2">
          <el-button type="primary" size="small" style="float: right;margin-bottom: 10px" @click="load_az('拣货')"><i
              class="el-icon-download"></i>拣货提成下载
          </el-button>
          <el-button type="primary" size="small" style="float: right;margin-bottom: 10px;margin-right: 10px"
                     @click="load_azer('拣货')"><i
              class="el-icon-download"></i>按拣货人员下载
          </el-button>
          <el-table :data="reportData" border height="calc(100vh - 350px)"
                    :headerCellStyle="{
              textAlign: 'center',
              'background': '#66b1ff',
              'color': 'white',
            }" :cellStyle="{ textAlign: 'center', 'font-size': '12px' }">
            <el-table-column prop="installers" label="拣货人员"></el-table-column>
            <el-table-column prop="areaName" label="所属仓库"></el-table-column>
            <el-table-column label="类型">
              <template slot-scope="scope">
                <span v-if="scope.row.orderType==1">新店</span>
                <span v-if="scope.row.orderType==2">老店</span>
              </template>
            </el-table-column>
            <el-table-column prop="storeName" label="店铺名称"></el-table-column>
            <el-table-column label="营业区转化图">
              <template v-slot:default="scope">
                <el-image
                    v-if="scope.row.cadImg"
                    style="width: 50px"
                    src="https://qiniushelves.jiachuangnet.com/shelf/img/%E6%9F%A5%E7%9C%8B%E8%AF%A6%E6%83%85.png"
                    :preview-src-list="Array('https://'+scope.row.cadImg)"
                ></el-image>
              </template>
            </el-table-column>
            <el-table-column label="仓库转化图">
              <template v-slot:default="scope">
                <el-image
                    v-if="scope.row.storageImg"
                    style="width: 50px"
                    src="https://qiniushelves.jiachuangnet.com/shelf/img/%E6%9F%A5%E7%9C%8B%E8%AF%A6%E6%83%85.png"
                    :preview-src-list="Array('https://'+scope.row.storageImg)"
                ></el-image>
              </template>
            </el-table-column>
            <el-table-column prop="commissionFee" label="单次提成"></el-table-column>
            <el-table-column prop="deliveryDate" label="安装日期"></el-table-column>
            <!--            <el-table-column label="总提成">-->
            <!--              <template slot-scope="scope">-->
            <!--                <span style="color: orangered">{{ (scope.row.totalCommissionFee).toFixed(2) }}</span>-->
            <!--              </template>-->
            <!--            </el-table-column>-->
            <el-table-column label="状态">
              <template slot-scope="scope">
                <span v-if="scope.row.isCancelCommission==0">正常</span>
                <span style="color: orangered" v-if="scope.row.isCancelCommission==1">已取消提成</span>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination style="padding: 20px 0;" align="right" @size-change="handleSizeChange"
                         @current-change="handleCurrentChange" :current-page="currentPage"
                         :page-sizes="[20, 30, 40, 50]"
                         layout="total, sizes, prev, pager, next, jumper" :total="totalCount">
          </el-pagination>
        </el-tab-pane>
        <el-tab-pane label="装车列表" name="3">
          <el-button type="primary" size="small" style="float: right;margin-bottom: 10px" @click="load_az('装车')"><i
              class="el-icon-download"></i>装车提成下载
          </el-button>
          <el-button type="primary" size="small" style="float: right;margin-bottom: 10px;margin-right: 10px"
                     @click="load_azer('装车')"><i
              class="el-icon-download"></i>按装车人员下载
          </el-button>
          <el-table :data="reportData" border height="calc(100vh - 350px)"
                    :headerCellStyle="{
              textAlign: 'center',
              'background': '#66b1ff',
              'color': 'white',
            }" :cellStyle="{ textAlign: 'center', 'font-size': '12px' }">
            <el-table-column prop="installers" label="装车人员"></el-table-column>
            <el-table-column prop="areaName" label="所属仓库"></el-table-column>
            <el-table-column label="类型">
              <template slot-scope="scope">
                <span v-if="scope.row.orderType==1">新店</span>
                <span v-if="scope.row.orderType==2">老店</span>
              </template>
            </el-table-column>
            <el-table-column prop="storeName" label="店铺名称"></el-table-column>
            <el-table-column label="营业区转化图">
              <template v-slot:default="scope">
                <el-image
                    v-if="scope.row.cadImg"
                    style="width: 50px"
                    src="https://qiniushelves.jiachuangnet.com/shelf/img/%E6%9F%A5%E7%9C%8B%E8%AF%A6%E6%83%85.png"
                    :preview-src-list="Array('https://'+scope.row.cadImg)"
                ></el-image>
              </template>
            </el-table-column>
            <el-table-column label="仓库转化图">
              <template v-slot:default="scope">
                <el-image
                    v-if="scope.row.storageImg"
                    style="width: 50px"
                    src="https://qiniushelves.jiachuangnet.com/shelf/img/%E6%9F%A5%E7%9C%8B%E8%AF%A6%E6%83%85.png"
                    :preview-src-list="Array('https://'+scope.row.storageImg)"
                ></el-image>
              </template>
            </el-table-column>
            <el-table-column prop="commissionFee" label="单次提成"></el-table-column>
            <el-table-column prop="deliveryDate" label="安装日期"></el-table-column>
            <!--            <el-table-column label="总提成">-->
            <!--              <template slot-scope="scope">-->
            <!--                <span style="color: orangered">{{ (scope.row.totalCommissionFee).toFixed(2) }}</span>-->
            <!--              </template>-->
            <!--            </el-table-column>-->
            <el-table-column label="状态">
              <template slot-scope="scope">
                <span v-if="scope.row.isCancelCommission==0">正常</span>
                <span style="color: orangered" v-if="scope.row.isCancelCommission==1">已取消提成</span>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination style="padding: 20px 0;" align="right" @size-change="handleSizeChange"
                         @current-change="handleCurrentChange" :current-page="currentPage"
                         :page-sizes="[20, 30, 40, 50]"
                         layout="total, sizes, prev, pager, next, jumper" :total="totalCount">
          </el-pagination>
        </el-tab-pane>
        <el-tab-pane label="卸货列表" name="4">
          <el-button type="primary" size="small" style="float: right;margin-bottom: 10px" @click="load_az('卸货')"><i
              class="el-icon-download"></i>卸货提成下载
          </el-button>
          <el-button type="primary" size="small" style="float: right;margin-bottom: 10px;margin-right: 10px"
                     @click="load_azer('卸货')"><i
              class="el-icon-download"></i>按卸货人员下载
          </el-button>
          <el-table :data="reportData" border height="calc(100vh - 350px)"
                    :headerCellStyle="{
              textAlign: 'center',
              'background': '#66b1ff',
              'color': 'white',
            }" :cellStyle="{ textAlign: 'center', 'font-size': '12px' }">
            <el-table-column prop="installers" label="卸货人员"></el-table-column>
            <el-table-column prop="areaName" label="所属仓库"></el-table-column>
            <el-table-column label="类型">
              <template slot-scope="scope">
                <span v-if="scope.row.orderType==1">新店</span>
                <span v-if="scope.row.orderType==2">老店</span>
              </template>
            </el-table-column>
            <el-table-column prop="storeName" label="店铺名称"></el-table-column>
            <el-table-column label="营业区转化图">
              <template v-slot:default="scope">
                <el-image
                    v-if="scope.row.cadImg"
                    style="width: 50px"
                    src="https://qiniushelves.jiachuangnet.com/shelf/img/%E6%9F%A5%E7%9C%8B%E8%AF%A6%E6%83%85.png"
                    :preview-src-list="Array('https://'+scope.row.cadImg)"
                ></el-image>
              </template>
            </el-table-column>
            <el-table-column label="仓库转化图">
              <template v-slot:default="scope">
                <el-image
                    v-if="scope.row.storageImg"
                    style="width: 50px"
                    src="https://qiniushelves.jiachuangnet.com/shelf/img/%E6%9F%A5%E7%9C%8B%E8%AF%A6%E6%83%85.png"
                    :preview-src-list="Array('https://'+scope.row.storageImg)"
                ></el-image>
              </template>
            </el-table-column>
            <el-table-column prop="commissionFee" label="单次提成"></el-table-column>
            <el-table-column prop="deliveryDate" label="安装日期"></el-table-column>
            <!--            <el-table-column label="总提成">-->
            <!--              <template slot-scope="scope">-->
            <!--                <span style="color: orangered">{{ (scope.row.totalCommissionFee).toFixed(2) }}</span>-->
            <!--              </template>-->
            <!--            </el-table-column>-->
            <el-table-column label="状态">
              <template slot-scope="scope">
                <span v-if="scope.row.isCancelCommission==0">正常</span>
                <span style="color: orangered" v-if="scope.row.isCancelCommission==1">已取消提成</span>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination style="padding: 20px 0;" align="right" @size-change="handleSizeChange"
                         @current-change="handleCurrentChange" :current-page="currentPage"
                         :page-sizes="[20, 30, 40, 50]"
                         layout="total, sizes, prev, pager, next, jumper" :total="totalCount">
          </el-pagination>
        </el-tab-pane>
        <el-tab-pane label="售后列表" name="5">
          <el-button type="primary" size="small" style="float: right;margin-bottom: 10px" @click="load_az('售后')"><i
              class="el-icon-download"></i>售后提成下载
          </el-button>
          <el-button type="primary" size="small" style="float: right;margin-bottom: 10px;margin-right: 10px"
                     @click="load_azer('售后')"><i
              class="el-icon-download"></i>按售后人员下载
          </el-button>
          <el-table :data="reportData" border height="calc(100vh - 350px)"
                    :headerCellStyle="{
              textAlign: 'center',
              'background': '#66b1ff',
              'color': 'white',
            }" :cellStyle="{ textAlign: 'center', 'font-size': '12px' }">
            <el-table-column prop="installers" label="售后人员"></el-table-column>
            <el-table-column prop="areaName" label="所属仓库"></el-table-column>
            <el-table-column label="类型">
              <template slot-scope="scope">
                <span v-if="scope.row.orderType==1">新店</span>
                <span v-if="scope.row.orderType==2">老店</span>
              </template>
            </el-table-column>
            <el-table-column prop="storeName" label="店铺名称"></el-table-column>
            <el-table-column label="营业区转化图">
              <template v-slot:default="scope">
                <el-image
                    v-if="scope.row.cadImg"
                    style="width: 50px"
                    src="https://qiniushelves.jiachuangnet.com/shelf/img/%E6%9F%A5%E7%9C%8B%E8%AF%A6%E6%83%85.png"
                    :preview-src-list="Array('https://'+scope.row.cadImg)"
                ></el-image>
              </template>
            </el-table-column>
            <el-table-column label="仓库转化图">
              <template v-slot:default="scope">
                <el-image

                    v-if="scope.row.storageImg"
                    style="width: 50px"
                    src="https://qiniushelves.jiachuangnet.com/shelf/img/%E6%9F%A5%E7%9C%8B%E8%AF%A6%E6%83%85.png"
                    :preview-src-list="Array('https://'+scope.row.storageImg)"
                ></el-image>
              </template>
            </el-table-column>
            <el-table-column prop="commissionFee" label="售后费用"></el-table-column>
            <!--            <el-table-column prop="deliveryDate" label="售后日期"></el-table-column>-->
            <el-table-column prop="afterSaleRemark" label="备注"/>
            <!--            <el-table-column label="总提成">-->
            <!--              <template slot-scope="scope">-->
            <!--                <span style="color: orangered">{{ (scope.row.totalCommissionFee).toFixed(2) }}</span>-->
            <!--              </template>-->
            <!--            </el-table-column>-->
            <el-table-column label="状态">
              <template slot-scope="scope">
                <span v-if="scope.row.isCancelCommission==0" v-prevent-re-click>正常</span>
                <span style="color: orangered" v-if="scope.row.isCancelCommission==1">已取消提成</span>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination style="padding: 20px 0;" align="right" @size-change="handleSizeChange"
                         @current-change="handleCurrentChange" :current-page="currentPage"
                         :page-sizes="[20, 30, 40, 50]"
                         layout="total, sizes, prev, pager, next, jumper" :total="totalCount">
          </el-pagination>
        </el-tab-pane>
      </el-tabs>


    </div>

  </div>
</template>

<script>
import dayjs from "dayjs";
import * as XLSX from "xlsx-js-style";
import Decimal from "decimal.js";
import quinn from "../../../utils/quinn";

export default {
  name: "ReportList",
  data() {
    return {
      sateValue: "",
      areaData: "",
      params: {},
      currentPage: 1,
      reportData: [],
      authority: [],
      systemTypeData: [],
      totalCount: 0,
      pageNumber: 1,
      pageSize: 20,
      activeName: "1",
      installers: "",
      systemType: "",
      areaId: "",
      isCancelCommission: "",
      storeName: "",
    }
  },
  created() {
    const {authorityList = []} = quinn.getStorage('userData')
    this.authority = authorityList
    this.getReportList()
    this.areaList()
  },
  methods: {
    areaList() {
      this.$api.areaLedgerAreaList().then(res => {
        this.areaData = res
      })
      this.$api.orderGetSystemTypeVo().then(res => {
        this.systemTypeData = res
      })
    },
    getReportList() {
      const data = {
        startTime: this.params.startTime || "",
        endTime: this.params.endTime || "",
        type: this.activeName,
        pageNumber: this.pageNumber,
        areaId: this.areaId,
        pageSize: this.pageSize,
        installers: this.installers,
        storeName: this.storeName,
        systemType: this.systemType
        // isCancelCommission:Number(this.isCancelCommission)
      }
      this.$api.orderGetCommissionListByType(data).then(res => {
// // 先按 installers 排序，使相同的安装人员相邻
//         const sortedData = res.data.sort((a, b) => a.installers.localeCompare(b.installers));
// // 遍历数据并计算相同 installers 的 commissionFee 总和
//         let totalCommissionMap = {};
//         sortedData.forEach(item => {
//           if (!totalCommissionMap[item.installers]) {
//             totalCommissionMap[item.installers] = 0;
//           }
//           totalCommissionMap[item.installers] += item.commissionFee;
//         });
//
// // 将commissionFee添加到每个数据项
//         const result = sortedData.map(item => ({
//           ...item,
//           totalCommissionFee: totalCommissionMap[item.installers]
//         }));

        this.reportData = res.data
        this.totalCount = res.total
      })
    },
    search() {
      const data = {
        startTime: this.params.startTime || "",
        endTime: this.params.endTime || "",
        type: this.activeName,
        pageNumber: 1,
        areaId: this.areaId,
        pageSize: this.pageSize,
        installers: this.installers,
        storeName: this.storeName,
        systemType: this.systemType
        // isCancelCommission:Number(this.isCancelCommission)
      }
      this.$api.orderGetCommissionListByType(data).then(res => {
// // 先按 installers 排序，使相同的安装人员相邻
//         const sortedData = res.data.sort((a, b) => a.installers.localeCompare(b.installers));
// // 遍历数据并计算相同 installers 的 commissionFee 总和
//         let totalCommissionMap = {};
//         sortedData.forEach(item => {
//           if (!totalCommissionMap[item.installers]) {
//             totalCommissionMap[item.installers] = 0;
//           }
//           totalCommissionMap[item.installers] += item.commissionFee;
//         });
//
// // 将commissionFee添加到每个数据项
//         const result = sortedData.map(item => ({
//           ...item,
//           totalCommissionFee: totalCommissionMap[item.installers]
//         }));

        this.reportData = res.data
        this.totalCount = res.total
      })
    },
    selectTime(val) {
      if (val) {
        this.params.startTime = dayjs(val[0]).format("YYYY-MM-DD");
        this.params.endTime = dayjs(val[1]).format("YYYY-MM-DD");
      } else {
        this.params.startTime = ''
        this.params.endTime = ''
      }
    },
    // objectSpanMethod({row, column, rowIndex, columnIndex}) {
    //   let spanOneArr = [];
    //   let concatOne = 0;
    //   this.reportData.map((item, index) => {
    //     if (index === 0) {
    //       spanOneArr.push(1);
    //     } else {
    //       //合并第一列 installers
    //       if (item.installers === this.reportData[index - 1].installers &&
    //           item.orderType === this.reportData[index - 1].orderType && item.totalCommissionFee === this.reportData[index - 1].totalCommissionFee) {
    //         spanOneArr[concatOne] += 1;
    //         spanOneArr.push(0);
    //       } else {
    //         spanOneArr.push(1);
    //         concatOne = index;
    //       }
    //       ;
    //     }
    //   });
    //
    //   //合并第一列和第二列
    //   if (columnIndex === 0 || columnIndex === 1 || columnIndex === 5) {
    //     const _row = spanOneArr[rowIndex];
    //     const _col = _row > 0 ? 1 : 0;
    //     return {
    //       rowspan: _row,
    //       colspan: _col
    //     };
    //   }
    // },
    handleSizeChange(val) {
      this.pageSize = val
      this.getReportList()
    },
    handleCurrentChange(val) {
      this.pageNumber = val
      this.getReportList()
    },
    // handleClick(tab, event) {
    //   console.log(this.activeName)
    //   const data = {
    //     startTime: this.params.startTime || "",
    //     endTime: this.params.endTime || "",
    //     type: this.activeName
    //   }
    //   this.$api.orderGetCommissionListByType(data).then(res => {
    //     const sortedData = res.data.sort((a, b) => a.installers.localeCompare(b.installers));
    //     this.reportData = sortedData
    //   })
    // },
    async downloadTotal(val) {
      if (!(this.params.startTime && this.params.endTime)) return this.$message.error("请选择开始时间和结束时间！")
      let params = {
        pageSize: 10000,
        pageNumber: 1,
        startTime: this.params.startTime,
        endTime: this.params.endTime,
        systemType: val
      }
      const res = await this.$api.orderGetCommissionSummary(params).then()
//以installers 作为唯一标识  数据汇总为commissionFee   type为1时取commissionFee1    4为commissionFee4
      const result = [];
      const map = new Map();
      res.data.forEach(item => {
        const {installers, type, commissionFee} = item;

        if (!map.has(installers)) {
          map.set(installers, {installers});
        }
        if (type === 1) {
          map.get(installers).commissionFee1 = commissionFee;
        } else if (type === 2) {
          map.get(installers).commissionFee2 = commissionFee;
        } else if (type === 3) {
          map.get(installers).commissionFee3 = commissionFee;
        } else if (type === 4) {
          map.get(installers).commissionFee4 = commissionFee;
        } else if (type === 5) {
          map.get(installers).commissionFee5 = commissionFee;
        }
      });
      result.push(...map.values());
      const wb = XLSX.utils.book_new();
      let data = [
        [this.params.startTime + "-" + this.params.endTime + '提成汇总'],
        ['姓名', '安装提成', '拣货提成', '装车提成', '卸货提成', '售后提成', "合计"]]
      result.map(el => {
        // el.total = Decimal(el.commissionFee1).plus(Decimal(el.commissionFee4)).toNumber();
        el.commissionFee1 ||= 0;
        el.commissionFee2 ||= 0;
        el.commissionFee3 ||= 0;
        el.commissionFee4 ||= 0;
        el.commissionFee5 ||= 0;
        el.count1 = Decimal(el.commissionFee1).plus(Decimal(el.commissionFee2)).toNumber();
        el.count2 = Decimal(el.commissionFee3).plus(Decimal(el.commissionFee4)).toNumber();
        el.count3 = Decimal(el.count1).plus(Decimal(el.count2)).toNumber();
        el.total = Decimal(el.count3).plus(Decimal(el.commissionFee5)).toNumber();
        data.push([el.installers, (el.commissionFee1), (el.commissionFee2), (el.commissionFee3), (el.commissionFee4), (el.commissionFee5), el.total])
      })
      const ws = XLSX.utils.aoa_to_sheet(data);
      ws['!cols'] = [
        {wpx: 100}, // 第一列宽度为250单位
        {wpx: 100},
        {wpx: 100},
        {wpx: 100},
        {wpx: 100},
        {wpx: 100},
        {wpx: 100},
      ];
      ws["A1"].s = {
        alignment: {horizontal: 'center'},
        font: {bold: true, color: {rgb: '000000'}},
        fill: {fgColor: {rgb: 'ff6a00'}}
      }
      const range = ['A2', 'B2', 'C2', 'D2', 'E2', 'F2']; // 目标单元格范围
      const style = {
        alignment: {horizontal: 'center'},
        font: {bold: true, color: {rgb: '000000'}},
        fill: {fgColor: {rgb: '3CB371'}}
      };

// 遍历每个单元格并应用样式
      range.forEach(cell => {
        ws[cell].s = style;
      });
      ws["A1"].hpt = 240;
      Object.keys(ws).forEach(cell => {
        if (cell[0] !== '!') { // 排除特殊属性，如 `!ref`
          if (!ws[cell].s) {
            ws[cell].s = {}; // 确保 `s` 存在
          }
          if (!ws[cell].s.alignment) {
            ws[cell].s.alignment = {};
          }
          ws[cell].s.alignment.horizontal = 'center';
        }
      });
      XLSX.utils.book_append_sheet(wb, ws, "提成汇总");
      ws['!merges'] = [
        {s: {r: 0, c: 0}, e: {r: 0, c: 5}},
      ]
      const wbout = XLSX.write(wb, {bookType: 'xlsx', type: 'binary'});
      // 创建一个 Blob 对象
      const blob = new Blob([s2ab(wbout)], {type: 'application/octet-stream'});
      // 使用 Blob 对象创建一个链接
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = `${this.params.startTime}-${this.params.endTime}提成汇总.xlsx`;

      // 触发下载
      link.click();

      // 清理
      URL.revokeObjectURL(link.href);

      function s2ab(s) {
        const buf = new ArrayBuffer(s.length);
        const view = new Uint8Array(buf);
        for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
        return buf;
      }


    },
    async load_az(val) {
      const params = {
        startTime: this.params.startTime || "",
        endTime: this.params.endTime || "",
        type: this.activeName,
        pageNumber: 1,
        areaId: this.areaId,
        pageSize: 100000,
        installers: this.installers,
        storeName: this.storeName,
        systemType: this.systemType
        // isCancelCommission:Number(this.isCancelCommission)
      }
      const resData = await this.$api.orderGetCommissionListByType(params).catch(() => null)
      // 1. 获取数据
      if (!resData?.data?.length) {
        this.$message.warning("暂无数据导出");
        return;
      }
      const sortedData = resData.data.sort((a, b) => a.storeName.localeCompare(b.storeName));
      // 遍历数据并计算相同 storeName 的 installers 总和
      let totalCommissionMap = {};
      sortedData.forEach(item => {
        if (item.isCancelCommission != 0) {
          item.commissionFee = 0
        }
        if (!totalCommissionMap[item.storeName]) {
          totalCommissionMap[item.storeName] = 0;
        }
        totalCommissionMap[item.storeName] += item.commissionFee;
      });
      // 将commissionFee添加到每个数据项
      const result = sortedData.map(item => ({
        ...item,
        totalCommissionFee: totalCommissionMap[item.storeName],
        isCancelCommissionStr: item.isCancelCommission === 0 ? "正常" : "已取消提成"
      }));
      result.sort((a, b) => (a.storeName || '').localeCompare(b.storeName || ''));
      // 3. 组装表格数据
      const header = ['店铺名称', '所属仓库', '该店总数', `${val}姓名`, `单次${val}费用`, `${val}日期`, '状态'];
      const sheetData = [
        [`${val}提成汇总`],
        header,
        ...result.map(el => [
          el.storeName,
          el.areaName,
          el.totalCommissionFee,
          el.installers,
          el.commissionFee,
          el.deliveryDate,
          el.isCancelCommissionStr
        ])
      ];
      // 4. 创建 Sheet
      const ws = XLSX.utils.aoa_to_sheet(sheetData);
// 设置第一列和第二列居中
      // 样式工具函数
      const setStyle = (cell, style) => {
        if (!ws[cell]) return;
        ws[cell].s = {...(ws[cell].s || {}), ...style};
      };

      // 标题行样式
      setStyle("A1", {
        alignment: {horizontal: "center"},
        font: {bold: true, color: {rgb: "000000"}},
        fill: {fgColor: {rgb: "FF6A00"}}
      });

      // 表头样式
      header.forEach((_, idx) => {
        const cell = String.fromCharCode(65 + idx) + "2"; // A2 ~ G2
        setStyle(cell, {
          alignment: {horizontal: "center"},
          font: {bold: true, color: {rgb: "000000"}},
          fill: {fgColor: {rgb: "3CB371"}}
        });
      });
      const range = XLSX.utils.decode_range(ws['!ref']) // 获取工作表范围
      for (let R = range.s.r; R <= range.e.r; R++) {
        for (let C = range.s.c; C <= range.e.c; C++) {
          const cellAddress = {r: R, c: C} // 获取单元格地址
          const cell = ws[XLSX.utils.encode_cell(cellAddress)]
          if (cell) {
            cell.s = cell.s || {} // 初始化样式
            cell.s.alignment = {
              horizontal: 'center', // 水平居中
              vertical: 'center', // 垂直居中
            }
          }
        }
      }

      // 列宽
      ws["!cols"] = Array(header.length).fill({wpx: 150});
      // 合并标题行
      ws["!merges"] = [{s: {r: 0, c: 0}, e: {r: 0, c: header.length - 1}}];
// 合并相同店铺名称（A列 = colIndex 0）
      this.mergeSameCells(ws, sheetData, 0);
      // this.mergeSameCells(ws, sheetData, 2);
      // 5. 生成工作簿
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, "提成汇总");
      // 6. 导出下载
      this.downloadExcel(wb, `${val}提成汇总.xlsx`);
    },
    async load_azer(val) {
      const params = {
        startTime: this.params.startTime || "",
        endTime: this.params.endTime || "",
        type: this.activeName,
        pageNumber: 1,
        areaId: this.areaId,
        pageSize: 100000,
        installers: this.installers,
        storeName: this.storeName,
        systemType: this.systemType
        // isCancelCommission:Number(this.isCancelCommission)
      }
      const resData = await this.$api.orderGetCommissionListByType(params).catch(() => null)
      const data = resData.data
      // 获取所有唯一的 installers 和 storeName
      const commissions = Array.from(
          new Set(data.map((item) => item.installers))
      )
      const stores = Array.from(new Set(data.map((item) => item.storeName)))
      const sheetData = []
      // 添加表头
      sheetData.push(['店铺名称', ...commissions])
      // 为每个 store 添加行
      stores.forEach((store) => {
        const row = [store]
        commissions.forEach((commission) => {
          const commissionData = data.find(
              (item) =>
                  item.storeName === store && item.installers === commission
          )
          row.push(commissionData ? commissionData.commissionFee : 0) // 如果找不到该项，填充 0
        })
        sheetData.push(row)
      })

      // 创建工作表和工作簿
      const ws = XLSX.utils.aoa_to_sheet(sheetData)
      const wb = XLSX.utils.book_new()
      XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
      ws['!cols'] = [
        {wpx: 200}, // 第一列宽度（Store Name列）
        ...commissions.map(() => ({wpx: 80})), // 其余列宽度
      ]
      // 设置居中对齐
      const range = XLSX.utils.decode_range(ws['!ref']) // 获取工作表范围
      for (let R = range.s.r; R <= range.e.r; R++) {
        for (let C = range.s.c; C <= range.e.c; C++) {
          const cellAddress = {r: R, c: C} // 获取单元格地址
          const cell = ws[XLSX.utils.encode_cell(cellAddress)]
          if (cell) {
            cell.s = cell.s || {} // 初始化样式
            cell.s.alignment = {
              horizontal: 'center', // 水平居中
              vertical: 'center', // 垂直居中
            }
          }
        }
      }
      // 生成并下载 Excel 文件
      XLSX.writeFile(wb, `${val}总提成表.xlsx`)

    },
    mergeSameCells(ws, data, colIndex, startRow = 2) {
      let merges = ws["!merges"] || [];
      let prevValue = null;
      for (let row = startRow; row < data.length; row++) {
        const value = data[row][colIndex];
        if (value === prevValue) {
          // 扩展上一段合并范围
          merges[merges.length - 1].e.r = row;
        } else {
          prevValue = value;
          merges.push({
            s: {r: row, c: colIndex},
            e: {r: row, c: colIndex}
          });
        }
      }
      ws["!merges"] = merges;
    },

    downloadExcel(wb, fileName) {
      const wbout = XLSX.write(wb, {bookType: "xlsx", type: "binary"});
      const s2ab = s => {
        const buf = new ArrayBuffer(s.length);
        const view = new Uint8Array(buf);
        for (let i = 0; i < s.length; i++) view[i] = s.charCodeAt(i) & 0xff;
        return buf;
      };
      const blob = new Blob([s2ab(wbout)], {type: "application/octet-stream"});
      const link = document.createElement("a");
      link.href = URL.createObjectURL(blob);
      link.download = fileName;
      document.body.appendChild(link);
      link.click();
      setTimeout(() => {
        URL.revokeObjectURL(link.href);
        document.body.removeChild(link);
      }, 100);
    },

  }
}
</script>

<style scoped>

</style>